const { ipcRenderer } = require('electron');

// 获取DOM元素
const taskForm = document.getElementById('task-form');
const taskIdInput = document.getElementById('task-id');
const taskTitleInput = document.getElementById('task-title');
const taskDescriptionInput = document.getElementById('task-description');
const taskPrioritySelect = document.getElementById('task-priority');
const taskDueDateInput = document.getElementById('task-due-date');
const taskStatusSelect = document.getElementById('task-status');
const taskHoursInput = document.getElementById('task-hours');
const saveTaskBtn = document.getElementById('save-task-btn');
const cancelTaskBtn = document.getElementById('cancel-task-btn');
const taskListContainer = document.getElementById('task-list-container');
const filterButtons = document.querySelectorAll('.filter-btn');
const closeBtn = document.getElementById('close-task-manager');

// 统计元素
const totalTasksSpan = document.getElementById('total-tasks');
const pendingTasksSpan = document.getElementById('pending-tasks');
const inProgressTasksSpan = document.getElementById('in-progress-tasks');
const completedTasksSpan = document.getElementById('completed-tasks');

// 当前筛选条件
let currentFilter = 'all';

// 初始化
window.addEventListener('DOMContentLoaded', () => {
    // 请求获取任务数据
    ipcRenderer.send('get-task-data');
    
    // 设置今天的日期为默认截止日期
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];
    taskDueDateInput.value = formattedDate;
});

// 监听从主进程发送的任务数据
ipcRenderer.on('task-data', (event, tasks) => {
    renderTasks(tasks);
    updateStats(tasks);
});

// 渲染任务列表
function renderTasks(tasks) {
    // 根据筛选条件过滤任务
    let filteredTasks = tasks;
    if (currentFilter === 'pending') {
        filteredTasks = tasks.filter(t => t.status === 'pending');
    } else if (currentFilter === 'in-progress') {
        filteredTasks = tasks.filter(t => t.status === 'in-progress');
    } else if (currentFilter === 'completed') {
        filteredTasks = tasks.filter(t => t.status === 'completed');
    } else if (currentFilter === 'overdue') {
        const now = new Date();
        filteredTasks = tasks.filter(t => {
            if (!t.dueDate || t.status === 'completed') return false;
            return new Date(t.dueDate) < now;
        });
    }
    
    // 清空任务列表
    taskListContainer.innerHTML = '';
    
    if (filteredTasks.length === 0) {
        taskListContainer.innerHTML = '<div class="no-tasks">暂无任务</div>';
        return;
    }
    
    // 渲染任务
    filteredTasks.forEach(task => {
        const taskElement = createTaskElement(task);
        taskListContainer.appendChild(taskElement);
    });
}

// 创建任务元素
function createTaskElement(task) {
    const taskItem = document.createElement('li');
    taskItem.className = `task-item ${task.status === 'completed' ? 'completed' : ''}`;
    taskItem.dataset.id = task.id;
    
    // 优先级文本
    const priorityText = {
        'low': '低',
        'medium': '中',
        'high': '高'
    };
    
    // 状态文本
    const statusText = {
        'pending': '待办',
        'in-progress': '进行中',
        'completed': '已完成'
    };
    
    // 检查是否逾期
    let isOverdue = false;
    if (task.dueDate && task.status !== 'completed') {
        const dueDate = new Date(task.dueDate);
        const now = new Date();
        isOverdue = dueDate < now;
    }
    
    taskItem.innerHTML = `
        <div class="task-item-header">
            <div class="task-item-title ${task.status === 'completed' ? 'completed' : ''}">
                ${task.title}
            </div>
            <div class="task-item-meta">
                <span class="priority-badge priority-${task.priority}">
                    ${priorityText[task.priority]}
                </span>
                <span class="status-badge status-${task.status}">
                    ${statusText[task.status]}
                </span>
            </div>
        </div>
        ${task.description ? `<div class="task-item-description">${task.description}</div>` : ''}
        ${task.dueDate ? `
            <div class="due-date ${isOverdue ? 'overdue' : ''}">
                截止日期: ${new Date(task.dueDate).toLocaleDateString('zh-CN')}
                ${isOverdue ? ' (已逾期)' : ''}
            </div>
        ` : ''}
        ${task.hours && task.hours > 0 ? `
            <div class="task-hours small">
                工时: ${task.hours}小时
            </div>
        ` : ''}
        <div class="task-item-actions">
            <button class="task-item-btn edit-task-btn" data-id="${task.id}">编辑</button>
            <button class="task-item-btn complete-task-btn" data-id="${task.id}">
                ${task.status === 'completed' ? '重新开始' : '完成'}
            </button>
            <button class="task-item-btn delete-task-btn" data-id="${task.id}">删除</button>
        </div>
    `;
    
    // 添加事件监听器
    taskItem.querySelector('.edit-task-btn').addEventListener('click', () => {
        editTask(task);
    });
    
    taskItem.querySelector('.complete-task-btn').addEventListener('click', () => {
        ipcRenderer.send('toggle-task-status', task.id);
    });
    
    taskItem.querySelector('.delete-task-btn').addEventListener('click', () => {
        if (confirm(`确定要删除任务"${task.title}"吗？`)) {
            ipcRenderer.send('delete-task', task.id);
        }
    });
    
    return taskItem;
}

// 编辑任务
function editTask(task) {
    taskIdInput.value = task.id;
    taskTitleInput.value = task.title;
    taskDescriptionInput.value = task.description || '';
    taskPrioritySelect.value = task.priority;
    taskStatusSelect.value = task.status;
    
    if (task.dueDate) {
        taskDueDateInput.value = new Date(task.dueDate).toISOString().split('T')[0];
    } else {
        const today = new Date();
        taskDueDateInput.value = today.toISOString().split('T')[0];
    }
    
    // 设置工时
    taskHoursInput.value = task.hours || '';
    
    // 滚动到表单顶部
    document.querySelector('.task-form-section').scrollIntoView({ behavior: 'smooth' });
}

// 保存任务
taskForm.addEventListener('submit', (e) => {
    e.preventDefault();
    
    const title = taskTitleInput.value.trim();
    if (!title) {
        alert('请输入任务标题');
        return;
    }
    
    const taskData = {
        title: title,
        description: taskDescriptionInput.value.trim(),
        priority: taskPrioritySelect.value,
        status: taskStatusSelect.value,
        dueDate: taskDueDateInput.value ? new Date(taskDueDateInput.value).toISOString() : null,
        hours: taskHoursInput.value ? parseFloat(taskHoursInput.value) : 0
    };
    
    const taskId = taskIdInput.value;
    if (taskId) {
        // 更新任务
        ipcRenderer.send('update-task', { id: parseInt(taskId), updates: taskData });
    } else {
        // 添加新任务
        ipcRenderer.send('add-task', taskData);
    }
    
    // 重置表单
    resetForm();
});

// 取消编辑
cancelTaskBtn.addEventListener('click', () => {
    resetForm();
});

// 重置表单
function resetForm() {
    taskForm.reset();
    taskIdInput.value = '';
    
    // 设置今天的日期为默认截止日期
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];
    taskDueDateInput.value = formattedDate;
}

// 筛选任务
filterButtons.forEach(button => {
    button.addEventListener('click', () => {
        // 更新活动按钮
        filterButtons.forEach(btn => btn.classList.remove('active'));
        button.classList.add('active');
        
        // 更新筛选条件
        currentFilter = button.dataset.filter;
        
        // 重新渲染任务
        ipcRenderer.send('get-task-data');
    });
});

// 更新统计信息
function updateStats(tasks) {
    totalTasksSpan.textContent = tasks.length;
    
    const pendingCount = tasks.filter(t => t.status === 'pending').length;
    pendingTasksSpan.textContent = pendingCount;
    
    const inProgressCount = tasks.filter(t => t.status === 'in-progress').length;
    inProgressTasksSpan.textContent = inProgressCount;
    
    const completedCount = tasks.filter(t => t.status === 'completed').length;
    completedTasksSpan.textContent = completedCount;
}

// 关闭窗口
closeBtn.addEventListener('click', () => {
    ipcRenderer.send('close-task-manager');
});

// 监听任务更新
ipcRenderer.on('tasks-updated', (event, tasks) => {
    renderTasks(tasks);
    updateStats(tasks);
});